﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Jermaine.Encrypt
{
    public class AESEncrypt : IEncrypt
    {
        private static readonly string _Key = "cma;eas!~-1?234'}/${c6a1`$#@!*&^)(";

        public String Encrypt(string text, string key) {
            try {

                var md5 = new MD5CryptoServiceProvider();
                var keyBytes = md5.ComputeHash(Encoding.Default.GetBytes(key));

                var textBytes = Encoding.Default.GetBytes(text);
                byte[] resultBytes = null;

                using (var rijndael = new RijndaelManaged()) {
                    rijndael.Key = keyBytes;
                    rijndael.Mode = CipherMode.ECB;
                    rijndael.Padding = PaddingMode.PKCS7;

                    var enc = rijndael.CreateEncryptor();

                    resultBytes = enc.TransformFinalBlock(textBytes, 0, textBytes.Length);

                }
                return Convert.ToBase64String(resultBytes, 0, resultBytes.Length);
            } catch {
                return string.Empty;
            }
        }

        public String Encrypt(string text) {
            return this.Encrypt(text, _Key);
        }

        public String Decrypt(string text, string key) {
            try {
                var md5 = new MD5CryptoServiceProvider();
                var keyBytes = md5.ComputeHash(Encoding.Default.GetBytes(key));

                var textBytes = Convert.FromBase64String(text);
                byte[] resultBytes = null;

                using (var rijndael = new RijndaelManaged()) {
                    rijndael.Key = keyBytes;
                    rijndael.Mode = CipherMode.ECB;
                    rijndael.Padding = PaddingMode.PKCS7;

                    var enc = rijndael.CreateDecryptor();
                    resultBytes = enc.TransformFinalBlock(textBytes, 0, textBytes.Length);
                }

                return Encoding.Default.GetString(resultBytes);
            } catch {
                return string.Empty;
            }
        }

        public String Decrypt(string text) {
            return Decrypt(text, _Key);
        }
    }
}
